package hng.mapper;

import hng.model.OrdersDO;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import hng.vo.OrderItemVO;
import hng.vo.OrderProductVO;
import hng.vo.store.OrdersVO;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;

import java.util.List;

/**
 * <p>
 * 订单表 Mapper 接口
 * </p>
 *
 * @author 告白
 * @since 2024-06-27
 */
public interface OrdersMapper extends BaseMapper<OrdersDO> {

    /**
     * 商家分页查询订单列表
     */
    @Select({
            "<script>",
            "SELECT u.username, u.avatar, o.* ",
            "FROM orders o ",
            "LEFT JOIN user u ON o.user_id = u.id ",
            "WHERE o.store_id = #{storeId} ",
            "<if test='orderStatus != null'> ",
            "AND o.order_status = #{orderStatus} ",
            "</if>",
            "ORDER BY o.create_time DESC ",
            "</script>"
    })
    List<OrdersVO> getListByStore(@Param("storeId") Integer storeId, @Param("orderStatus") Integer orderStatus);

    /**
     * 管理员分页查询订单列表
     */
    @Select("SELECT u.username, u.avatar, o.* " +
            "FROM orders o " +
            "LEFT JOIN user u ON o.user_id = u.id " +
            "ORDER BY o.create_time DESC")
    List<OrdersVO> getListByAdmin();

    /**
     * 商家查询总交易金额
     */
    @Select("select sum(total_amount) " +
            "from orders " +
            "where store_id = #{storeId}")
    Double moneyTotalByStore(@Param("storeId") Integer storeId);

    /**
     * 管理员查询总交易金额
     */
    @Select("select sum(total_amount) from orders ")
    Double moneyTotalByAdmin();

    /**
     * 通过订单id查找商品详情
     */

    @Select("SELECT p.id AS productId, p.name, p.price, p.detail, p.category_id AS categoryId, p.cover_url AS coverUrl, " +
            "oi.product_num AS productNum, oi.product_spec AS productSpec, " +
            "o.total_amount AS totalAmount, o.id AS orderId, o.order_status AS orderStatus, o.create_time AS createTime " +
            "FROM product p " +
            "JOIN order_item oi ON p.id = oi.product_id " +
            "JOIN orders o ON oi.order_id = o.id " +
            "WHERE o.id = #{orderId}")
    List<OrderProductVO> getProductsByOrderId(@Param("orderId") Integer orderId);

    /**
     * 用户查询订单详情
     */
    @Select("SELECT i.id, i.order_id, i.product_id, i.product_spec, i.product_num, i.product_price, p.cover_url, p.name as product_name " +
            "FROM order_item i " +
            "LEFT JOIN product p ON i.product_id = p.id " +
            "WHERE i.order_id = #{orderId}")
    List<OrderItemVO> selectOrderItems(Integer orderId);
}
